package com.yaoyong.yy_demo.module.wechat;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;

public class CheckBrowser {

    /**
     * 判断是否是微信浏览器或者支付宝浏览器，或者普通浏览器
     *
     * @param request
     * @return
     */
    public static int check(HttpServletRequest request) {
        String browsers = request.getHeader("user-agent").toLowerCase();
        if (browsers.indexOf("micromessenger") > 0) {
            //微信浏览器
            return 1;
        } else if (browsers.indexOf("alipayclient") > 0) {
            //支付宝浏览器
            return 2;
        } else {
            //普通浏览器
            return 0;
        }
    }

    /**
     * 判断是否是手机端
     *
     * @param request
     * @return
     */
    public static boolean isMobile(HttpServletRequest request) {
        String browsers = request.getHeader("user-agent").toLowerCase();
        if (browsers.indexOf("mobile") > 0) {
            //手机端
            return true;
        } else {
            //PC端
            return false;
        }
    }

    /**
     * 设置请求参数编码格式
     *
     * @param response
     * @param request
     */
    public static void setRespOrReq(HttpServletResponse response, HttpServletRequest request) {
        try {
            if (response != null) {
                response.setDateHeader("Expires", 0);
                response.setHeader("Cache-Controll", "no-cache");
                response.setHeader("pragma", "no-cache");
                response.setContentType("application/json;charset=utf-8");
            }

            if (request != null) {
                request.setCharacterEncoding("utf-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送响应流方法
     */
    public static void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}
